﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CodeRepositoryConsole.FCL.IO
{
    public static class ByteArrayToFileTestDriver
    {
        const string TEST_FILEPATH = "Data/logisticsCompany.xml";

        public static void Test()
        {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, TEST_FILEPATH);
            // Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
            byte[] bytes = File.ReadAllBytes(path);

            string destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WriteAllBytes.xml");
            
            //--------------- Test  WriteByWriteAllBytes ---------//
            ByteArrayToFile instance = new ByteArrayToFile();
            instance.WriteByWriteAllBytes(destPath, bytes);

            destPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "BinaryWriter.xml");
            instance.WriteByBinaryWriter(destPath, bytes);
        }
    }

    class ByteArrayToFile
    {

        /// <summary>
        /// write to file by File.WriteAllBytes
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="bytes"></param>
        /// <see cref="https://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx"/>
        /// <see cref="https://stackoverflow.com/questions/381508/can-a-byte-array-be-written-to-a-file-in-c"/>
        public void WriteByWriteAllBytes(string filePath, byte[] bytes)
        {
            // Creates a new file, writes the specified byte array to the file, and then closes the file. 
            // If the target file already exists, it is overwritten.
            File.WriteAllBytes(filePath, bytes);
        }

        /// <summary>
        /// Write to file by BinaryWriter
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="bytes"></param>
        public void WriteByBinaryWriter(string filePath, byte[] bytes)
        {
            // BinaryWriter is disposable so should probably be used within an using block.
            // But this method I want to use try/finally block.

            BinaryWriter bw = null;
            try
            {
                bw = new BinaryWriter(File.Open(filePath, FileMode.OpenOrCreate));
                bw.Write(bytes);                
                bw.Flush();
                bw.Close();
            }
            finally
            {
                bw.Dispose();
            }
        }

    }
}
